#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pcap replay daemon
# chkconfig: 345 20 80
# description: Replays packet capture data stored in libpcap format
# processname: pcap-replay
#

DAEMON_PATH="{{ pcap_replay_home }}"
PCAPIN=`ls $DAEMON_PATH/*.pcap 2> /dev/null`
IFACE="{{ pcap_replay_interface }}"
EXTRA_ARGS="${@:2}"
NAME=pcap-replay
DESC="Replay packet capture data"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
LOGFILE=/var/log/$NAME.log

case "$1" in
  start)
    printf "%-50s" "Starting $NAME..."

    # ensure that a pcap file exists to replay
    if [ -z "$PCAPIN" ]; then
      printf "%s: %s\n" "Fail: No pcap files found at " $DAEMON_PATH
    else
      # kick-off the daemon
      cd $DAEMON_PATH
      DAEMON="{{ tcpreplay_prefix }}/bin/tcpreplay"
      DAEMONOPTS="--intf1=$IFACE --loop=0 $EXTRA_ARGS $PCAPIN"
      PID=`$DAEMON $DAEMONOPTS > $LOGFILE 2>&1 & echo $!`
      if [ -z $PID ]; then
          printf "%s\n" "Fail"
      else
          echo $PID > $PIDFILE
          printf "%s\n" "Ok"
      fi
    fi
  ;;

  status)
    printf "%-50s" "Checking $NAME..."
    if [ -f $PIDFILE ]; then
      PID=`cat $PIDFILE`
      if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
        printf "%s\n" "Process dead but pidfile exists"
      else
        echo "Running"
      fi
    else
      printf "%s\n" "Service not running"
    fi
  ;;

  stop)
    printf "%-50s" "Stopping $NAME"
    PID=`cat $PIDFILE`
    cd $DAEMON_PATH
    if [ -f $PIDFILE ]; then
      while sleep 1
        echo -n "."
        kill -0 $PID >/dev/null 2>&1
      do
        kill $PID
      done
      printf "%s\n" "Ok"
      rm -f $PIDFILE
    else
        printf "%s\n" "pidfile not found"
    fi
  ;;

  restart)
    $0 stop
    $0 start
  ;;

  *)
    echo "Usage: $0 {status|start|stop|restart}"
    exit 1
esac
